﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DB_Test.ServiceReference1;
using System.Globalization;

namespace DB_Test
{
	/// <summary>
	/// Interaction logic for OrderViewPanel.xaml
	/// </summary>
	public partial class OrderViewPanel : UserControl
    {
        #region Initialization
        public OrderViewPanel()
		{
			InitializeComponent();
            Loaded += new RoutedEventHandler(OrderViewPanel_Loaded);
            IsVisibleChanged += new DependencyPropertyChangedEventHandler(OrderViewPanel_IsVisibleChanged);
        }
        #endregion

        #region Properties
        public bool ShoudUpdateDB
        {
            get
            {
                return (bool)GetValue(ShoudUpdateDBProperty);
            }
            set
            {
                SetValue(ShoudUpdateDBProperty, value);
            }
        }
		public int SelectedProductID
		{
			get
			{
				return (int)GetValue(SelectedProductIDProperty);
			}
			set
			{
				SetValue(SelectedProductIDProperty, value);
			}
		}
        #endregion

        #region Dependency properties
        internal static readonly DependencyProperty ShoudUpdateDBProperty
            = DependencyProperty.Register("ShoudUpdateDB", typeof(bool), typeof(OrderViewPanel));
		internal static readonly DependencyProperty SelectedProductIDProperty
			= DependencyProperty.Register("SelectedProductID", typeof(int), typeof(OrderViewPanel), new PropertyMetadata(-1));
        #endregion

        #region Implementation
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
			if(HasErrors())
			{
				return;
			}

			float discount;
			float.TryParse(xDiscountTxt.Text, System.Globalization.NumberStyles.Float, NumberFormatInfo.InvariantInfo, out discount);

            short quantity;
            short.TryParse(xQuantityTxt.Text, out quantity);

            DateTime reqiuredDate;
            DateTime.TryParse(xRequiredDateTxt.Text, out reqiuredDate);

            DateTime shippedDate;
            DateTime.TryParse(xShippedDateTxt.Text, out shippedDate);

			int shipVia;
			int.TryParse(xShipViaTxt.Text, out shipVia);

			decimal freight;
			decimal.TryParse(xFreightTxt.Text, out freight);

			if(string.IsNullOrEmpty( xCompanyNameTxt.Text) &&
				string.IsNullOrEmpty( xCompanyNameCombo.Text))
			{
				MessageBox.Show("Please, select the company.", "", MessageBoxButton.OK, MessageBoxImage.Warning);
				return;
			}

			if(string.IsNullOrEmpty( xProductNameCombo.Text))
			{
				MessageBox.Show("Please, select the product.", "", MessageBoxButton.OK, MessageBoxImage.Warning);
				return;
			}

            var client = new WCFServiceClient();
            try
            {
                client.Open();

				CustomersClass customer = GetCustomerFromInput(client);				
				OrdersClass order = new OrdersClass
				{
					Customer = customer,
					OrderDate = DateTime.Now,
					RequiredDate = reqiuredDate,
					ShippedDate = shippedDate,
					ShipVia = shipVia,
					ShipName = xShipNameTxt.Text,
					ShipAddress = xShipAddressTxt.Text,
					Freight = freight
				};

				client.AddOrder(order);

				OrdersClass orderFromDB = client.GetOrderByInstance(order);
				ProductsClass product = client.GetProduct(xProductNameCombo.Text);

				OrderDetailsClass orderDetails = new OrderDetailsClass
				{
 					Order = orderFromDB,
					Product = product,
					Discount = discount,
					Quantity = quantity,
					UnitPrice = product.UnitPrice.Value
				};

				client.AddOrderDetails(orderDetails);
            }
            finally
            {
                client.Close();
            }

            ShoudUpdateDB = true;
            ClearInputExt();
            UpdateDataContext();
        }

		private bool HasErrors()
		{
			return (Validation.GetErrors(xCompanyNameTxt).Count > 0 && xCompanyNameCombo.SelectedIndex == -1) ||
					xProductNameCombo.SelectedIndex == -1 ||
					Validation.GetErrors(xQuantityTxt).Count > 0 ||
					Validation.GetErrors(xDiscountTxt).Count > 0;
		}

		private CustomersClass GetCustomerFromInput(WCFServiceClient client)
		{
			CustomersClass customer;
			if (!string.IsNullOrEmpty(xCompanyNameTxt.Text))
			{
				customer = AddNewCustomer(client);
			}
			else
			{
				customer = client.GetCustomer(xCompanyNameCombo.Text);
			}
			return customer;
		}

		private CustomersClass AddNewCustomer(WCFServiceClient client)
		{
			CustomersClass newCustomer = new CustomersClass
			{
				CompanyName = xCompanyNameTxt.Text,
				ContactName = xContactNameTxt.Text,
				Address = xAddressTxt.Text,
				Phone = xPhoneTxt.Text
			};

			client.AddCustomer(newCustomer);
			newCustomer = client.GetCustomer(newCustomer.CompanyName);
			
			UpdateCustomers(client);
			return newCustomer;
		}

        internal void ClearInput()
        {
            xCompanyNameCombo.SelectedIndex = -1;
            xProductNameCombo.SelectedIndex = -1;
            xQuantityTxt.ClearValue(TextBlock.TextProperty);
            xDiscountTxt.ClearValue(TextBlock.TextProperty);
            xRequiredDateTxt.ClearValue(TextBlock.TextProperty);
            xShippedDateTxt.ClearValue(TextBlock.TextProperty);
            xShipViaTxt.ClearValue(TextBlock.TextProperty);
            xShipNameTxt.ClearValue(TextBlock.TextProperty);
            xShipAddressTxt.ClearValue(TextBlock.TextProperty);
            xFreightTxt.ClearValue(TextBlock.TextProperty);

            xCompanyNameTxt.ClearValue(TextBlock.TextProperty);
            xContactNameTxt.ClearValue(TextBlock.TextProperty);
            xAddressTxt.ClearValue(TextBlock.TextProperty);
            xPhoneTxt.ClearValue(TextBlock.TextProperty);
        }

        internal void ClearInputExt()
        {
            ClearInput();

            xCompanyNameCombo.SelectedIndex = -1;
            xProductNameCombo.SelectedIndex = -1;
            xQuantityTxt.Text = "";
            xDiscountTxt.Text = "";
            xRequiredDateTxt.Text = "";
            xShippedDateTxt.Text = "";
            xShipViaTxt.Text = "";
            xShipNameTxt.Text = "";
            xShipAddressTxt.Text = "";
            xFreightTxt.Text = "";

            xCompanyNameTxt.Text = "";
            xContactNameTxt.Text = "";
            xAddressTxt.Text = "";
            xPhoneTxt.Text = "";

			xNewCustomerExpander.IsExpanded = false;
        }
        
        private void OrderViewPanel_Loaded(object sender, RoutedEventArgs e)
        {
            var client = new WCFServiceClient();

            try
            {
                client.Open();
				UpdatePanelInfo(client);
            }
            finally
            {
                client.Close();
            }
        }

		internal void UpdatePanelInfo(WCFServiceClient client)
		{
			UpdateProducts(client);
			UpdateCustomers(client);
		}

        internal void UpdateProducts()
        {
            var client = new WCFServiceClient();

            try
            {
                client.Open();
                UpdateProducts(client);
            }
            finally
            {
                client.Close();
            }
        }

        internal void UpdateProducts(WCFServiceClient client)
        {
            xProductNameCombo.ItemsSource = client.GetProducts();

            if(SelectedProductID != -1)
            {
                var sp = (from p in xProductNameCombo.Items.OfType<ProductsClass>()
                          where p.ProductID == SelectedProductID
                          select p).FirstOrDefault();

                xProductNameCombo.SelectedItem = sp;
            }
        }

        internal void UpdateCustomers()
        {
            var client = new WCFServiceClient();

            try
            {
                client.Open();
                UpdateCustomers(client);
            }
            finally
            {
                client.Close();
            }
        }

        internal void UpdateCustomers(WCFServiceClient client)
        {
            xCompanyNameCombo.ItemsSource = client.GetCustomers();
        }

        private void OrderViewPanel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (IsVisible)
            {
                UpdateDataContext();
            }
            else
            {
                DataContext = null;
            }
            
        }

        private void UpdateDataContext()
        {
            DataContext = new ProductsOnOrderFullInfoClass();
        }

        #endregion
    }
}
